package com.wgtest.controller;

import com.alibaba.fastjson.JSONObject;
import com.wgtest.pojo.Msg;
import com.wgtest.pojo.Operatin;
import com.wgtest.pojo.RequestParameter;
import com.wgtest.pojo.WeixinParam;
import com.wgtest.utils.*;
import com.wgtest.service.Liushuiserviceimpl;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

@RestController
@RequestMapping("/wangguan")
public class MyController
{
    //参数对象
    @Autowired
    RequestParameter requestParameter;
    @Resource
    Liushuiserviceimpl liushuiserviceimpl;
    @Resource
    WeixinParam weixinParam;
        //转发支付请求
    @RequestMapping("/zhifu")//接收4个参数
    public Msg zhifu(@RequestBody RequestParameter  parame) throws Exception {
        requestParameter.setNotify_url("http://538s69k093.qicp.vip/wangguan/huidiao");
        requestParameter.setReturn_url(parame.getReturn_url());
        requestParameter.setTimestamp(parame.getSubject());
        JSONObject js = new JSONObject();
        js.put("out_trade_no",parame.getOut_trade_no());
        js.put("product_code",requestParameter.getProduct_code());
        js.put("subject", parame.getSubject());
        js.put("total_amount", parame.getTotal_amount());
        js.put("return_url",requestParameter.getReturn_url());
        js.put("notify_url",requestParameter.getNotify_url());
        requestParameter.setBiz_content(js);
        //获取treemap
        TreeMap treeMap = Paixu.getTreeMap(requestParameter);
        //获取待生成签名
        String sifnStr = Paixu.getSifnStr(treeMap);
        sifnStr = sifnStr.substring(1);
        //生成签名
        String signqm = Scqm.signqm(sifnStr, requestParameter.getMerchant_private_key());
        if(signqm !=null)
        {
            treeMap.put("sign",signqm);
        }

        Msg msg = new Msg();
        String getparam = Paixu.getparam(treeMap);
        getparam = getparam.substring(1);
        //记流水表
        Operatin operatin = new Operatin();
        operatin.setOrderId(parame.getOut_trade_no());
        Double aDouble = Double.valueOf(parame.getTotal_amount());
        BigDecimal bigDecimal = BigDecimal.valueOf(aDouble);
        operatin.setOrderMoney(bigDecimal);
        operatin.setOrderStatus("1");//未支付
        operatin.setHuidiao(parame.getNotify_url());
        liushuiserviceimpl.addorder(operatin);
        //拼接from表单
        String s = Paixu.formPost(treeMap);
        msg.setMsg("ok");
        msg.setData(s);
        msg.setCode(200);
        return msg;
    }

    //支付宝H5接口
    @RequestMapping("/h5zhifu")
    public Msg h5zhifu(@RequestBody RequestParameter  parame) throws Exception {
        requestParameter.setNotify_url("http://538s69k093.qicp.vip/wangguan/huidiao");
        requestParameter.setReturn_url(parame.getReturn_url());
        requestParameter.setTimestamp(parame.getSubject());
        requestParameter.setMethod("alipay.trade.wap.pay");
        JSONObject js = new JSONObject();
        js.put("out_trade_no",parame.getOut_trade_no());
        js.put("product_code",requestParameter.getProduct_code());
        js.put("subject", parame.getSubject());
        js.put("total_amount", parame.getTotal_amount());
        js.put("return_url",requestParameter.getReturn_url());
        js.put("notify_url",requestParameter.getNotify_url());
        requestParameter.setBiz_content(js);
        //获取treemap
        TreeMap treeMap = Paixu.getTreeMap(requestParameter);
        //获取待生成签名
        String sifnStr = Paixu.getSifnStr(treeMap);
        sifnStr = sifnStr.substring(1);
        //生成签名
        String signqm = Scqm.signqm(sifnStr, requestParameter.getMerchant_private_key());
        if(signqm !=null)
        {
            treeMap.put("sign",signqm);
        }

        Msg msg = new Msg();
        String getparam = Paixu.getparam(treeMap);
        getparam = getparam.substring(1);
        //记流水表
        Operatin operatin = new Operatin();
        operatin.setOrderId(parame.getOut_trade_no());
        Double aDouble = Double.valueOf(parame.getTotal_amount());
        BigDecimal bigDecimal = BigDecimal.valueOf(aDouble);
        operatin.setOrderMoney(bigDecimal);
        operatin.setOrderStatus("1");//未支付
        operatin.setHuidiao(parame.getNotify_url());
        liushuiserviceimpl.addorder(operatin);
        //拼接from表单
        String s = Paixu.formPost(treeMap);
        msg.setMsg("ok");
        msg.setData(s);
        msg.setCode(200);
        return msg;
    }
    //微信H5接口
    @RequestMapping("/h5zhifu2")
    public Msg h5zhifu2(@RequestBody(required = false) WeixinParam param) throws Exception {
        weixinParam.setBody("body");
        String orderIdByTime = OrderId.getOrderIdByTime();
        weixinParam.setOut_trade_no(orderIdByTime);
        weixinParam.setNonce_str(orderIdByTime);
        weixinParam.setTotal_fee("1");
        JSONObject json = new JSONObject();
        json.put("type","Wap");
        json.put("wap_url","https://pay.qq.com");
        json.put("wap_name","腾讯充值");
        JSONObject json2 = new JSONObject();
        json2.put("h5_info",json);
        String s = json2.toJSONString();
        weixinParam.setScene_info(s);
        Msg msg = new Msg();
        TreeMap treeMap2 = Paixu.getTreeMap2(weixinParam);
        String sifnStr = Paixu.getSifnStr(treeMap2);
        sifnStr = sifnStr.substring(1);
        sifnStr =sifnStr+"&key=ggy101600ggy101600ggy101600ggy10";
        String sign = SignUtil.MD5(sifnStr);
        treeMap2.put("sign",sign);
        String s1 = Paixu.GetMapToXML(treeMap2);
        //记流水表
//        Operatin operatin = new Operatin();
//        operatin.setOrderId(param.getOut_trade_no());
//        String total_fee = param.getTotal_fee();
//        Integer integer = Integer.valueOf(total_fee);
//        BigDecimal bigDecimal = BigDecimal.valueOf(integer);integer
//        operatin.setOrderMoney(bigDecimal);
//        operatin.setOrderStatus("1");//未支付
//        operatin.setHuidiao(param.getNotify_url());
//        liushuiserviceimpl.addorder(operatin);

        //发送请求
        HttpUtil httpUtil = new HttpUtil("https://api.mch.weixin.qq.com/pay/unifiedorder");
        httpUtil.setXmlParam(s1);
        httpUtil.setHttps(true);
        httpUtil.post();
        String content = httpUtil.getContent();
        Map<String, String> stringStringMap = Paixu.readStringXmlOut(content);
        String mweb_url = stringStringMap.get("mweb_url");
        String url ="http://m.jnbat.com:8189/wxhd.html?id=22";
        url =URLEncoder.encode(url);
        mweb_url =mweb_url+"&redirect_url="+url;
        msg.setCode(200);
        msg.setMsg("ok");
        msg.setData(mweb_url);
        return msg;
    }
    //支付宝回调接口
    @RequestMapping("/huidiao")
    public void huidiao(@RequestParam() Map<String,String> map) throws IOException {

        JSONObject js = new JSONObject();
        Set<String> set = map.keySet();
        for (String s : set) {
            js.put(s,map.get(s));
        }
        String out_trade_no = map.get("out_trade_no");
        //先查询流水表是否已支付避免二次回调
        String queryoreder = liushuiserviceimpl.queryoreder(out_trade_no);
        if(queryoreder.equals("1"))
        {
            //修改流水表状态
            liushuiserviceimpl.update0rder(out_trade_no);
            //获取到商城回调网址
            String quereywangzhi = liushuiserviceimpl.quereywangzhi(out_trade_no);
            //跳转到商城回调
            CloseableHttpClient client = HttpClientBuilder.create().build();
            String s1 = js.toJSONString();
            HttpPost httpPost = new HttpPost(quereywangzhi);
            StringEntity stringEntity = new StringEntity(s1, "utf-8");
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Content-Type","application/json;charset=utf8");
            CloseableHttpResponse response = null;
            try{
                // 由客户端执行(发送)Post请求
                response = client.execute(httpPost);
                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();

            }catch (Exception e)
            {

            }
            finally {
                // 释放资源
                if (client != null) {
                    client.close();
                }
                if (response != null) {
                    response.close();
                }
            }
        }
    }
    //微信网关回调
    @RequestMapping("/wxhuidiao")
    public void wxhuidiao(@RequestParam() Map<String,String> map){
        System.out.println(map);
    }

}
